package ui;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;

import model.JavaFileExtension;
import model.VersionInvestigator;


public class FileChooserPanel extends JPanel{


	private static final long serialVersionUID = 1L;
	
	JFileChooser fc;
	
	VersionInvestigator investigator;
	
	private FileChooserPanel() {
		FileFilter filter = new JavaRelatedFileFilter();
		
		fc = new JFileChooser();
		fc.setFileFilter(filter);
	}
	
	
	
	public FileChooserPanel(VersionInvestigator investigator) {
		this();
		this.investigator = investigator;
	}

	public void showChooser() {
		int returnVal = fc.showOpenDialog(FileChooserPanel.this);
		
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            String path = file.getAbsolutePath();
            System.out.println("Abs path: " + path );
            investigator.addArtifactPath(path);
            investigator.investigate();
        } else {
        	// canceled choosing file
        }
	}

	
	private static class JavaRelatedFileFilter extends FileFilter {

		@Override
		public boolean accept(File f) {
			if (f != null && f.getName() != null) {
				String path = f.getAbsolutePath();
				
				if(f.isDirectory()) {
					return true;
				}
				else if(JavaFileExtension.hasJavaFileExtension(path)) {
					return true;
				}
				else  {
					return false;
				}
			}
			else {
				return false;
			}
		}

		@Override
		public String getDescription() {
			return "All Java Files (*.class;*.jar;*.war;*.ear)";
		}
	}
	
    public void createAndShowGUI() {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Turn off metal's use of bold fonts
                UIManager.put("swing.boldMetal", Boolean.FALSE); 
            	FileChooserPanel.this.showChooser();
            }
        });
    }
 
}
